package net.esj.auth.inst.hibernate.dependent.background.manage;

import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import net.esj.auth.inst.hibernate.dependent.background.menu.AuthMenu;
import net.esj.auth.inst.ssh.manage.AuthManagerImpl;
import net.esj.auth.pojo.CoreAdmin;
import net.esj.auth.pojo.CoreAuthFunc;
import net.esj.background.manage.MenuManage;
import net.esj.background.support.BgMenu;
import net.esj.basic.pojo.system.UserRule;
import net.esj.basic.service.provider.UserRuleProvider;
import net.esj.basic.utils.SessionKeyConstants;

import org.apache.commons.lang.StringUtils;

public class MenuManageImpl extends AuthManagerImpl implements MenuManage,AuthBgMenu {

	/**
	 * true ：每次都重新加载
	 */
	private boolean reload = false;
	
	@Override
	public Set<BgMenu> getMenus() {
		Set<BgMenu> menus;
		Map userBag = (Map) getAgentContext().getSession().getAttribute(getSessionBag());
		if(!isReload()){
			if(userBag!=null){
				menus =(Set<BgMenu>) userBag.get(BG_MENU_SESSION_KEY);
				if(menus!=null){
					return menus;
				}
			}
		}
		CoreAdmin admin = (CoreAdmin) getAgentContext().getSession().getAttribute(getSessionKey());
		if(admin==null){
			return Collections.EMPTY_SET;
		}
		menus = new LinkedHashSet<BgMenu>();
		for(CoreAuthFunc func : admin.getAllowedFunctions()){
			if(func.isDisabled()){
				continue;
			}
			if(func.getParent()==null){//根目录
				BgMenu root = new AuthMenu(func); 
				menus.add(root);
				setChild(root, admin.getAllowedFunctions());
			}
		}
		if(userBag==null){
			userBag = new HashMap();
		}
		userBag.put(BG_MENU_SESSION_KEY, menus);
		getAgentContext().getSession().setAttribute(getSessionBag(), userBag);
		return menus;
	}

	private void setChild(BgMenu parent ,List<CoreAuthFunc> list){
		for(CoreAuthFunc bm : list){
			if(bm.isDisabled()){
				continue;
			}
			if(bm.getParent()!=null &&  StringUtils.equals(bm.getParent().getId(), parent.getId())){
				BgMenu m = new AuthMenu(bm);
				parent.getChildMenus().add(m);
				if(m.isMenu()){
					setChild(m, list);
				}
			}
		}
	}

	public boolean isReload() {
		return reload;
	}

	public void setReload(boolean reload) {
		this.reload = reload;
	}
	
	protected String getSessionKey(){
		UserRule rule = UserRuleProvider.getUserRule(CoreAdmin.class);
		if(rule!=null){
			return rule.getSessionKey();
		}
		return SessionKeyConstants.LOGIN_USER;
	}
	
	protected String getSessionBag(){
		UserRule rule = UserRuleProvider.getUserRule(CoreAdmin.class);
		if(rule!=null){
			return rule.getSessionBag();
		}
		return null;
	}

	@Override
	public String getLoginMessage() {
		return "";
	}
	
}
